package com.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.dao.ClazzDao;
import com.model.Clazz;
import com.model.ClazzProanswer;
import com.model.Paper;
import com.model.Student;
import com.util.CompareTime;
import com.util.Pagination;

@Repository("ClazzDao")
public class ClazzDaoImpl implements ClazzDao {

    @Resource
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public List<Clazz> ClazzList(Clazz clazz) {
        Session session = sessionFactory.getCurrentSession();
        // Criteria criteria = session.createCriteria("com.model.Clazz");
        // criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        // List<Clazz> l = criteria.list();

        Query q = session.createQuery("from Clazz");
        List<Clazz> l = q.list();
        return l;
    }

    @Override
    public List<Student> getStuListByclazzid(int id) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Student s where 1=1 and s.clazz.id = " + id;
        Query query = session.createQuery(hql);
        List<Student> l = query.list();
        return l;
    }

    @Override
    public void addClazz(Clazz clazz) {
        Session session = sessionFactory.getCurrentSession();
        session.save(clazz);

    }

    @Override
    public Clazz findByClazznum(int classnum) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Clazz c where 1=1 and c.classnum = " + classnum;
        Query query = session.createQuery(hql);
        List<Clazz> l = query.list();
        if (l.size() == 0) {
            return null;
        }
        return l.get(0);
    }

    @Override
    public Clazz findClazzById(int parseInt) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Clazz c where c.id=" + parseInt;
        Query query = session.createQuery(hql);
        List<Clazz> list = new ArrayList<Clazz>();
        list = query.list();
        if (list.isEmpty()) {
            return null;
        }

        return list.get(0);

    }

    @Override
    public Student StuInfo(int id) {
        Session session = sessionFactory.getCurrentSession();
        Student stu = (Student) session.get(Student.class, id);
        return stu;
    }

    @Override
    public Student teaEditInfo(int sid, String pas, String stuname) {
        Session session = sessionFactory.getCurrentSession();
        Student stu = (Student) session.get(Student.class, sid);
        stu.setPassword(pas);
        stu.setStuname(stuname);
        return stu;
    }

    @Override
    public void addStudent(Student student) {
    	String sno = student.getUsername();
    	String pwd = student.getPassword();
    	Student s = getStuBySNOPWD(sno,pwd);
    	if(s!=null){
    		student.setPassword(s.getPassword());
    	}
        
        Session session = sessionFactory.getCurrentSession();
        String sql = "insert into db_student(username , password , stuname , classid ) values('"+student.getUsername()+"','"+student.getPassword()+"','"+student.getStuname()+"','"+student.getClazz().getId()+"') ";
        session.createSQLQuery(sql).executeUpdate();
        
    }

    @Override
    public void delStudent(int id) {
        Session session = sessionFactory.getCurrentSession();
        Student stu = (Student) session.get(Student.class, id);
        session.delete(stu);
    }

    @Override
    public void delClazzById(int id) {
        Session session = sessionFactory.getCurrentSession();
        Clazz clazz = (Clazz) session.get(Clazz.class, id);
        session.delete(clazz);

    }

    @Override
    public List<Student> checkNameExitByClazzid(Student stu, int id) {
        Session session = sessionFactory.getCurrentSession();
        List<Student> list = new ArrayList<Student>();
        String hql = "from Student stu where stu.username = '" + stu.getUsername() + "' and stu.clazz.id = " + id;
        return session.createQuery(hql).list();

    }

    @Override
    public Pagination StuScore(ClazzProanswer proanswer, Pagination paperPage, int id) {
        if (proanswer.getPaper().getPapername() == null) {
            proanswer.getPaper().setPapername("");
        }
        if (proanswer.getStudent().getUsername() == null) {
            proanswer.getStudent().setUsername("");
        }

        String hql = "select p.paper.id, p.paper.papername,p.student.username,p.student.stuname,sum(p.score),p.student.id from ClazzProanswer p where p.student.clazz.id = " + id
                + " and p.paper.papername like '%" + proanswer.getPaper().getPapername() + "%' and p.student.username like '%" + proanswer.getStudent().getUsername() + "%' ";

        if (proanswer.getPaper().getId() != null) {
            hql = hql + "and p.paper.id = " + proanswer.getPaper().getId();
        }
        hql = hql + " group by p.paper.id, p.student.id";

        try {
            Session session = sessionFactory.getCurrentSession();
            Query q = session.createQuery(hql);
            paperPage.setTotal(q.list().size());
            paperPage.setTotalpagecountByhand();

            q.setFirstResult((paperPage.getCurrentpage() - 1) * paperPage.getPagesize());
            q.setMaxResults(30);
            paperPage.setList(q.list());
            return paperPage;
        } catch (RuntimeException re) {
            throw re;
        }

    }

    @Override
    public List paperInfo(int uid, int pid) {

        Session session = sessionFactory.getCurrentSession();
        String hql;

        hql = "select pro.programming.title ,pro.programming.score, pro.programming.content, pro.programming.inputdescribe, pro.programming.outputdescribe, pro.programming.inputsample, pro.programming.outputsample,"
                + "pro.programming.runtimeforjava, pro.programming.memoryforjava, pro.programming.runtime, pro.programming.memoryforc, "
                + "pro.answer,pro.score  from ClazzProanswer pro where pro.student.id = " + uid + " and pro.paper.id=" + pid;

        Query q = session.createQuery(hql);
        return q.list();

    }

    @Override
    public List getPaperBycid(int id) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "select c.papers from Clazz c  where c.id = " + id;
        Query q = session.createQuery(hql);
        List l = q.list();
        
        CompareTime comparaTime = new CompareTime(); // 打印状态

        for (int i = 0; i < l.size(); i++) {
            Paper p = (Paper) l.get(i);

            if (p.getBegintime() != null && p.getEndtime() != null) {
                p.setStatus(comparaTime.compareToTime(p.getBegintime(), p.getEndtime()));
            } else {
                p.setStatus("forever");
            }
        }
        return l;
    }

    @Override
    public void delPaperClazz(int cid, Integer paperId) {
        String sql = "delete from db_paperclass where paperid = " + paperId + " and classid = " + cid;
        Session session = sessionFactory.getCurrentSession();
        session.createSQLQuery(sql).executeUpdate();

    }

	@Override
	public List<Clazz> getAllClazzList(String sno) {
		Session session = sessionFactory.getCurrentSession();
        String hql = "select c from Clazz c ,Student s where s.clazz.id = c.id and s.username = '"+sno+"' ";
        Query q = session.createQuery(hql);
        List l = q.list();
        return l;
	}

	@Override
	public Student getStu(String sno, String clazzid) {
		Session session = sessionFactory.getCurrentSession();
		Query q = session.createQuery("from Student where username = '"+sno+"' and clazz.id =  "+clazzid);
	    List<Student> l = q.list();
	    return l.isEmpty() ? null : l.get(0);
	}

	@Override
	public Student getStuBySNOPWD(String sno, String pwd) {
		Session session = sessionFactory.getCurrentSession();
		Query q = session.createQuery("from Student where username = '"+sno+"' and password !=  "+pwd);
        List<Student> l = q.list();
		return l.isEmpty() ? null : l.get(0);
	}

}
